package fit.conceptmap.controller;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import fit.conceptmap.entities.User;
import fit.conceptmap.services.IUserService;

@Controller
@SessionAttributes({"username", "role" })
public class LoginController {
	private Logger logger = Logger.getLogger(LoginController.class);
	
	@Autowired IUserService userService;
	
	@RequestMapping(value = "/Welcome", method = RequestMethod.GET)
	public String goWelcomeDoGet(Model model) {
		System.out.println("1");
		return "Welcome";
	}
	@RequestMapping(value = "/Welcome", method = RequestMethod.POST)
	public String goWelcomeDoPost(Model model) {
		System.out.println("2");
		return "Welcome";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String goLogin(Model model) {
		System.out.println("3");
		return "Welcome";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String goLogin2(Model model) {
		System.out.println("3");
		return "Welcome";
	}
	
	@RequestMapping(value = "/loginfail", method = RequestMethod.GET)
	public String goLoginFail(Model model) {
		logger.info("Login Fail!");
		return "Welcome";
	}
	
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public String goHome(Model model) {
		logger.info("Go Home!");
		String url = "";
		// Get username - add session user
		org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username = user.getUsername();

		// Set sessopm user
		model.addAttribute("username", username);
		// Get role - add session rolesuser
		Collection<GrantedAuthority> authorities = user.getAuthorities();

		// Redirect
		User usr = userService.getUserByUsername(username);
	
		if (authorities.toString().contains("ROLE_ADMIN")) {
			// Set sessopm roleuser
			model.addAttribute("role", "admin");
			url = "admin/admin-home";
		} else {
			model.addAttribute("role", "user");
			url = "conceptmaps";
		}

		return url;
	}
}
